import axios from "axios";
import {
  Notification,
  MessageBox,
  Message
} from "element-ui";
// 创建axios实例

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 120000, // 请求超时时间
  method: "post"
});
service.interceptors.request.use(
  config => {

    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const code = response.status;
    if (code < 200 || code > 300) {
      Notification.error({
        title: "服务端接口错误",
        duration: 5000
      });
      return Promise.reject("error");
    } else {
      const res = response.data.data.result;
      if (res.publicData.retInfo.retMsg === "登录失效，请先登录") {
        MessageBox.confirm(res.publicData.retInfo.retMsg, "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.sessionStorage.removeItem("uuid");
          window.location.reload();
        });
      } else {
        return res;
      }
    }
  },
  error => {
    let code = 0;
    try {
      code = error.response.status;
      if (error.response.status >= 500) {
        Notification.error({
          title: "网络请求超时",
          duration: 5000
        });
      }
    } catch (e) {
      if (error.toString().indexOf("Error: timeout") !== -1) {
        Notification.error({
          title: "网络请求超时",
          duration: 5000
        });
        return Promise.reject(error);
      }
    }
    if (code === 502) {
      Notification.error({
        title: "网络请求超时",
        duration: 5000
      });
    }
    return Promise.reject(error);
  }
);
export default service;
